// pages/mobile-bind/mobile-bind.js
const app = getApp()
var store = require("../../utils/storageUtil.js")
const constant = require("../../constant.js")
const storage = require("../../utils/storage.js")
var util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: "mobile",
    codeMsg: '获取验证码',
    disableGetCode: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      host: constant.api(app.globalData.pord).url
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  switchForm: function () {
    var that = this;
    that.setData({
      form: that.data.form == "email" ? "mobile" : "email"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  inputMobile: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },

  inputEmail: function (e) {
    this.setData({
      email: e.detail.value
    })
  },

  getCode: function (e) {
    var that = this;
    if (!that.validMobile()) {
      return
    }

    that.setData({
      disableGetCode: true
    })

    var seconds = 60;
    var interval = setInterval(function (e) {
      seconds--;
      if (seconds < 0) {
        that.setData({
          disableGetCode: false,
          codeMsg: "重新获取验证码"
        })
        clearInterval(interval);
      } else {
        that.setData({
          codeMsg: "发送中（" + seconds + "）秒"
        })
      }
    }, 1000)

    wx.request({
      url: that.data.host + '/sms/verify-code?mobile=' + that.data.mobile,
      method: 'POST',
      success: function (res) {
        util.formatResponse(res, function (data) {
          that.setData({
            token: data.token
          })
        }, function (code, message) {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 1000
          })
          that.setData({
            disableGetCode: false,
            codeMsg: "获取验证码"
          })
          clearInterval(interval);
        })
      }
    })
  },

  inputCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  formSubmit: function (e) {
    var that = this;

    if (!that.validMobile()) {
      return
    }

    if (!that.validEmail()) {
      return
    }

    if (that.data.form == 'mobile') {
      if (!that.data.code) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none',
          duration: 1000
        })
        return
      } else if (that.data.code.length != 6) {
        wx.showToast({
          title: '验证码不正确',
          icon: 'none',
          duration: 1000
        })
        return
      }
    }

    var url;
    if (that.data.form == 'mobile') {
      url = that.data.host + '/login?unionid=' + wx.getStorageSync(storage.keys.unionid) +
        "&mobile=" + that.data.mobile +
        "&code=" + that.data.code +
        "&token=" + that.data.token +
        "&openid=" + wx.getStorageSync(storage.keys.openid);
    } else {
      url = that.data.host + '/login-by-email?unionid=' + wx.getStorageSync(storage.keys.unionid) +
        '&email=' + that.data.email +
        '&openid=' + wx.getStorageSync(storage.keys.openid);
    }
    wx.request({
      url: url,
      method: 'POST',
      success: function (res) {
        var responseData = typeof res === 'string' ? JSON.parse(res) : res;
        var isStudent = responseData.data.code == 0 ? responseData.data.data.isStudent : false;
        util.formatResponse(res, function (isStudent) {
          store.setSync(storage.keys.mobile, that.data.mobile, function () {
            wx.showToast({
              title: '绑定成功',
              icon: 'success',
              duration: 1000,
              mask: true,
              success: function () {
                wx.reLaunch({
                  url: '../../pages/product/detail/detail'
                })
              }
            });
          }, function () {
            wx.showToast({
              title: res.data.data.message,
              icon: 'none',
              duration: 1000,
              mask: true
            })
          });

        }, function (code, message) {
          wx.showToast({
            title: '绑定失败',
            icon: 'none',
            duration: 1000,
            mask: true
          })
        })
      }
    })
  },

  validMobile: function () {
    var that = this;

    if (that.data.form == 'mobile') {
      if (!that.data.mobile) {
        wx.showToast({
          title: '请输入手机号码',
          icon: 'none',
          duration: 1000
        })
        return false;
      } else if (!/^((13)|(15)|(16)|(17)|(18)|(19))\d{9}$/.test(that.data.mobile)) {
        wx.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
          duration: 1000
        })
        return false;
      }
    }

    return true;
  },

  validEmail: function () {
    var that = this;

    if (that.data.form == 'email') {
      if (!that.data.email) {
        wx.showToast({
          title: '请输入邮箱',
          icon: 'none',
          duration: 1000
        })
        return false;
      } else {
        var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

        if (!reg.test(that.data.email)) {
          wx.showToast({
            title: '请输入正确的邮箱',
            icon: 'none',
            duration: 1000
          })
          return false;
        }
      }
    }

    return true;
  }
})